package ru.xeden.core.common.listeners;

import java.util.ArrayList;
import java.util.List;


public class ListenerContainer<T extends IEvent>
{
    private List<IEventListener<T>> listeners;

    public ListenerContainer()
    {
        this.listeners = new ArrayList<IEventListener<T>>();
    }

    public void add(IEventListener<T> listener)
    {
        synchronized (listeners)
        {
            if (!listeners.contains(listener))
            {
                listeners.add(listener);
            }
        }
    }

    public void remove(IEventListener<T> listener)
    {
        synchronized (listeners)
        {
            listeners.remove(listener);
        }
    }

    @SuppressWarnings("unchecked")
    public void notify(T event)
    {
        Object [] arrLocal;
        synchronized (listeners)
        {
            arrLocal = listeners.toArray();
        }
        for (int i = arrLocal.length - 1; i >= 0; i--)
        {
            ((IEventListener<T>)arrLocal[i]).onEvent(event);
        }
    }
}
